import { Box, Flex, VStack } from '@chakra-ui/react';
import { useEffect, useRef } from 'react';
import MessageBubble, { Message } from './MessageBubble';

interface MessageListProps {
  messages: Message[];
  loading?: boolean;
}

const MessageList = ({ messages, loading = false }: MessageListProps) => {
  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages]);

  return (
    <Flex 
      direction="column" 
      flex="1" 
      overflowY="auto" 
      p={4}
      maxH="calc(100vh - 180px)"
    >
      <VStack spacing={4} align="stretch" w="100%">
        {messages.map((message) => (
          <MessageBubble key={message.id} message={message} />
        ))}
      </VStack>
      {loading && (
        <MessageBubble 
          message={{
            id: 'loading',
            content: '正在思考...',
            sender: 'ai',
            timestamp: new Date()
          }} 
        />
      )}
      <Box ref={bottomRef} />
    </Flex>
  );
};

export default MessageList;
